<?php

namespace app\admin\controller\system;

use app\common\controller\AdminController;
use app\services\system\SystemAdminService;
use EasyAdmin\tool\CommonTool;
use jianyan\excel\Excel;
use think\App;
use think\facade\Db;

/**
 * Class SystemAdmin
 * @package app\admin\controller\system
 */
class SystemAdmin extends AdminController
{
    /**
     * @var SystemAdminService
     */
    private $service;

    public function __construct(App $app, SystemAdminService $service)
    {
        parent::__construct($app);

        $this->service = $service;

        $this->assign('getStatusList', $this->service->getStatusList());

    }

    public function index()
    {
        if ($this->request->isAjax()) {
            return layuiTabSuc($this->service->getAdminList($this->request->get()));
        }
        return $this->fetch();
    }

    public function add()
    {
        if ($this->request->isAjax()) {
            $this->model->save($this->request->post());
            layuiTabSuc('保存成功');
        }
        return $this->fetch();
    }

    public function edit(int $id)
    {
        $row = $this->service->get($id);
        empty($row) && $this->error('数据不存在');

        if ($this->request->isAjax()) {
            $row->save($this->request->post());
            layuiTabSuc('保存成功');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    public function delete($id)
    {
        $this->service->delete($id);
        layuiTabSuc('删除成功');
    }

    public function export()
    {
        $tableName = $this->model->getName();
        $tableName = CommonTool::humpToLine(lcfirst($tableName));
        $prefix    = config('database.connections.mysql.prefix');
        $dbList    = Db::query("show full columns from {$prefix}{$tableName}");
        $header    = [];
        foreach ($dbList as $vo) {
            $comment = !empty($vo['Comment']) ? $vo['Comment'] : $vo['Field'];
            if (!in_array($vo['Field'], $this->noExportFields)) {
                $header[] = [$comment, $vo['Field']];
            }
        }
        $list = $this->service->getList($this->request->get());
        return Excel::exportData($list, $header, time(), 'xlsx');
    }

}